@echo off
setlocal enabledelayedexpansion

REM One-click script to install packages (via CN mirror), run app, and build EXE
REM All output messages are in English per requirement.

set MIRROR=https://pypi.tuna.tsinghua.edu.cn/simple
set VENV_DIR=.venv
set VENV_PY=%VENV_DIR%\Scripts\python.exe
set VENV_PIP=%VENV_DIR%\Scripts\pip.exe

if "%~1"=="install" goto :install
if "%~1"=="run" goto :run
if "%~1"=="build" goto :build

:menu
cls
ECHO ===============================================
ECHO  NCM2MP3 - One Click Operations
ECHO ===============================================
ECHO 1) Install dependencies (CN mirror)
ECHO 2) Run GUI program
ECHO 3) Build EXE with PyInstaller
ECHO 4) Exit
ECHO -----------------------------------------------
set /p choice=Select an option [1-4]: 
if "%choice%"=="1" goto :install
if "%choice%"=="2" goto :run
if "%choice%"=="3" goto :build
if "%choice%"=="4" goto :end
ECHO Invalid option. Try again.
goto :menu

:ensure_venv
if exist "%VENV_DIR%" goto :venv_done
ECHO Creating virtual environment...
python -m venv "%VENV_DIR%"
if errorlevel 1 (
    ECHO Failed to create virtual environment. Ensure Python is installed and in PATH.
    goto :end
)
:venv_done
if not exist "%VENV_PY%" (
    ECHO Virtual environment seems broken.
    goto :end
)
exit /b 0

:install
call :ensure_venv
ECHO Installing dependencies from requirements.txt (CN mirror)...
"%VENV_PIP%" install -i %MIRROR% -r requirements.txt
if errorlevel 1 (
    ECHO Dependency installation failed.
    goto :end
)
ECHO Installing PyInstaller (CN mirror)...
"%VENV_PIP%" install -i %MIRROR% pyinstaller
if errorlevel 1 (
    ECHO PyInstaller installation failed.
    goto :end
)
ECHO Installation completed successfully.
goto :menu

:run
call :ensure_venv
ECHO Launching GUI program...
"%VENV_PY%" main.py
if errorlevel 1 (
    ECHO Program exited with errors.
) else (
    ECHO Program exited normally.
)
goto :menu

:build
call :ensure_venv
ECHO Building EXE with PyInstaller...
"%VENV_PY%" -m PyInstaller --noconfirm --onefile --name ncm2mp3-gui --clean main.py
if errorlevel 1 (
    ECHO Build failed.
    goto :end
)
ECHO Build succeeded. Output: .\dist\ncm2mp3-gui.exe
ECHO You can run the EXE directly.
goto :menu

:end
ECHO Bye.
exit /b 0